package com.ludomancy.sos64.components;

import java.awt.Graphics;
import java.awt.Point;
import com.ludomancy.gamelib.ImageStrip;
import com.ludomancy.gamelib.ResourceManager;
import com.ludomancy.gamelib.Sound;
import com.ludomancy.sos64.Accumulator;
import com.ludomancy.sos64.Component;
import com.ludomancy.sos64.Game;

public class Egg extends Component
{
	private ImageStrip egg;
	private ImageStrip redegg;
	
	private boolean buried = true;
	private Accumulator hatching = new Accumulator(1500);
	private int hatchStage = 0;
	private boolean isHatching = false;
	public boolean isEmpty = false;
	
	public Egg(Point pos)
	{
		super(pos.x,pos.y);
		egg = new ImageStrip(ResourceManager.getImage("egg.png"), 12, 14);
		redegg = new ImageStrip(ResourceManager.getImage("egg_red.png"), 12, 14);
	}
	
	public Point getSize()
	{
		return new Point(12,14);
	}
	
	public boolean available()
	{
		return !buried;
	}

	public void paint(Graphics g, int px, int py)
	{
		if(!buried)
		{
			if(isHatching)
			{
				redegg.paint(g, hatchStage, px, py);
			}
			else
			{
				egg.paint(g, hatchStage, px, py);
			}
		}
	}
	
	public boolean isOrganic()
	{
		return true;
	}
	
	public void update()
	{
		Point tile = Game.game.tileFor(new Point(x,y));
		if(!Game.game.terrain.isBreakable(tile.x, tile.y))
		{
			buried = false;
		}
		if(buried && Game.game.terrain.isWater(tile.x, tile.y))
		{
			// die
			Game.game.components.remove(this);
		}
		// hatch?
		boolean heated = false;
		if(Game.game.isClose(this, 130, Recycler.class) != null)
		{
			heated = true;
		}
		
		if(heated && hatchStage < 2)
		{
			isHatching = true;
			hatching.update();
			if(hatching.isDone())
			{
				hatchStage ++;
				hatching.reset();
				if(hatchStage == 2)
				{
					isEmpty = true;
					// birth!
					Sound.play("grow.wav");
					Game.game.add(new Larva64(new Point(x-5,y-5)));
				}
			}
		}
		else
		{
			isHatching = false;
			hatching.reset();
		}
			
	}
}
